package com.icw.decoupling.defi.tool;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.icw.decoupling.defi.expand.TimerJob;
import com.icw.decoupling.defi.proxy.GenericSrvProxy;
import com.icw.resource.inner.entity.IcwTimerJob;
import com.icw.utility.BeanCtxUtils;
import com.icw.utility.IcwUtils;
import com.icw.utility.query.IcwCriteria;

public interface TimerJobManager {

	void start(IcwTimerJob timerTask) throws Exception;

	void stop(IcwTimerJob timerTask) throws Exception;

	static final Map<String, TimerJob> map = IcwUtils.tryCatch(() -> IcwUtils.instanceMap(TimerJob.class, new LinkedHashMap<String, TimerJob>()));

	static TimerJob getInstance(String name) throws Exception {
		TimerJob tj = map.get(name);
		if (tj == null) {
			throw new Exception("Job[" + name + "] does not exist.");
		} else {
			return tj;
		}
	}

	static void persistData() throws Exception {
		GenericSrvProxy srv = BeanCtxUtils.getBeanByType(GenericSrvProxy.class);
		for (Entry<String, TimerJob> entry : map.entrySet()) {
			String name = entry.getKey();
			if (srv.countByCriteria(IcwTimerJob.class, new IcwCriteria("eq", "name", name)) == 0) {
				TimerJob tj = entry.getValue();
				IcwTimerJob timerJob = new IcwTimerJob();
				timerJob.setName(tj.getName());
				timerJob.setCron(tj.getCron());
				timerJob.setIfRunning(tj.getIfRunning());
				srv.save(timerJob);
			}
		}
	}

	static void startAll() throws Exception {
		GenericSrvProxy srv = BeanCtxUtils.getBeanByType(GenericSrvProxy.class);
		List<IcwTimerJob> list = srv.query(IcwTimerJob.class, new IcwCriteria(), null);
		TimerJobManager ttm = BeanCtxUtils.getBeanByType(TimerJobManager.class);
		for (IcwTimerJob temp : list) {
			if (temp.getIfRunning()) IcwUtils.tryCatch(() -> ttm.start(temp));
		}
	}
}
